package daybook.model;

import daybook.model.transaction.Transaction;
import daybook.model.transaction.TransactionEntry;

import java.util.Comparator;
import java.util.Optional;

public final class Comparators {
    private Comparators() {}

    public static <T> Comparator<Optional<T>> makeComparator(Comparator<T> comparator) {
        return (ot1, ot2) -> {
            if (ot1.isPresent()) {
                if (ot2.isPresent()) {
                    return comparator.compare(ot1.get(), ot2.get());
                } else {
                    return 1;
                }
            } else {
                if (ot2.isPresent()) {
                    return -1;
                } else {
                    return 0;
                }
            }
        };
    }

    public final static Comparator<Account> accountComparator = Comparator
            .comparing(Account::getType)
            .thenComparing(Account::getCode);

    public final static Comparator<TransactionEntry> itemComparator = Comparator
            .comparing(TransactionEntry::getAccount, accountComparator)
            .thenComparing(p -> p.getDc() != p.getAccount().getType().getNormalBalance())
            .thenComparing(TransactionEntry::getAmount)
            .thenComparing(TransactionEntry::getDescription);

    public final static Comparator<Transaction> transactionComparator = Comparator
            .comparing(Transaction::getDate)
            .thenComparing(Transaction::getOrder);
}
